package com.tianma.celue.componet;

import com.tianma.celue.domain.User;
import com.tianma.celue.service.IBaseServiceHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author lgc
 * @createDate 2020/6/29 - 17:28
 */
@Component
public class CaCheTemplete {

    @Autowired
    private RedisTemplate redisTemplate;
    @PostConstruct
    void init(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
    }

    public <T> T loadCache(String key, IBaseServiceHandle<T> service) {

        T result =(T) redisTemplate.opsForValue().get(key);
        if (null == result){
            synchronized (this){
                result =(T)  redisTemplate.opsForValue().get(key);
                if (null == result){
                    System.out.println("查询数据库");
                    result = service.loadData();
                    redisTemplate.opsForValue().set(key,result);
                }
            }
        }

        return result;
    }

}
